﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; 
using System.Security.Cryptography;
using System.Windows;
using System.Collections;
using System.Threading;
using System.Globalization;
using TaskScheduler;

namespace instrument
{
    public class intrument
    {
        public intrument()
        {

        }
        /// <summary>
        /// 切割字符串
        /// </summary>
        void subString()
        {
            string str;
            string source = "the source";
            //IndexOf 获取这个字符最先在位置
            //sub切
            str = source.Substring(source.IndexOf('t'));
        }

        /// <summary>
        /// 获取ip
        /// </summary>
        /// <add>using System.Net;
        /// using System.Net.Sockets;</add>
        /// <returns>ip</returns>
        public string getIP()  //获得本机IP
        {
           
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
        }


        /// <summary>
        /// 将双精度的数值字符串保留小数点一位，若小数点后为0不保留。
        /// </summary>
        /// <param name="value">双精度的数值字符串。</param>
        /// <returns>新数值字符串。</returns>
        public static string DoubleStringConvert(string value)
        {
            double num = double.Parse(value);
            value = string.Format("{0:F1}" , num);
            value = value.TrimEnd(new char[] { '.' , '0' });
            if (value == "")
                value = "0";
            return value;
        }

        /// <summary>
        /// 获取文件的编码方式。
        /// 注：无法识别不带BOM的UTF8编码方式。
        /// 会将其误认为是Default编码方式，以致读取会出现乱码。
        /// </summary>
        /// <param name="fileName">文件名。</param>
        /// <returns>编码方式。</returns>
        public static Encoding GetFileEncoding(string fileName)
        {
            using (FileStream fs = new FileStream(
                fileName , FileMode.Open , FileAccess.Read))
            {
                if (fs.Length >= 2)
                {
                    byte[] data = new byte[2];
                    fs.Seek(0 , SeekOrigin.Begin);
                    fs.Read(data , 0 , 2);
                    if (data[0] == 255 && data[1] == 254)
                    {
                        fs.Close();
                        return Encoding.Unicode;
                    }
                    if (data[0] == 254 && data[1] == 255)
                    {
                        fs.Close();
                        return Encoding.BigEndianUnicode;
                    }
                }
                if (fs.Length >= 3)
                {
                    byte[] data = new byte[3];
                    fs.Seek(0 , SeekOrigin.Begin);
                    fs.Read(data , 0 , 3);
                    if (data[0] == 239 && data[1] == 187 &&
                        data[2] == 191)
                    {
                        fs.Close();
                        return Encoding.UTF8;
                    }
                }
                fs.Close();
                return Encoding.Default;
            }
        }

        /// <summary>
        /// 获取配置文件中的值，找不到返回空字符串，不返回null。
        /// </summary>
        /// <param name="file">配置文件名。</param>
        /// <param name="section">条目。</param>
        /// <param name="key">键。</param>
        /// <returns>值。</returns>
        public string ReadIniSection(
            string file , Encoding enc , string section , string key)
        {
            string value = "";
            if (!File.Exists(file))
                return value;
            using (StreamReader sr = new StreamReader(file , enc))
            {
                bool find = false;
                while (true)
                {
                    string text = sr.ReadLine();
                    if (text == null)
                        break;
                    text = text.Trim();
                    bool temp = text.StartsWith("[") && text.EndsWith("]");
                    if (find)
                    {
                        if (temp)
                            break;
                        string[] values = text.Split('=');
                        if (values.Length != 2 || values[0] != key)
                            continue;
                        value = values[1];
                        break;
                    }
                    else if (temp)
                    {
                        find = text.Substring(1 , text.Length - 2) == section;
                    }
                }
            }
            return value;
        }

        /// <summary>
        /// 字符串多匹配项替换。
        /// </summary>
        /// <param name="str">原字符串。</param>
        /// <param name="rp_s">匹配项组。</param>
        /// <param name="rp_t">替换项组。</param>
        /// <returns>替换后的字符串，若参数违法返回原字符串。</returns>
        public string MulitReplace(string str , string[] rp_s , string[] rp_t)
        {
            if (string.IsNullOrEmpty(str) || rp_s == null || rp_t == null)
            {
                //MessageBox.Show("参数不能为空！");
                return str;
            }
            if (rp_s.Length != rp_t.Length)
            {
                //MessageBox.Show("匹配项与替换项不符！");
                return str;
            }
            int t = rp_s.Length;
            for (int i = 0; i < t; i++)
            {
                if (string.IsNullOrEmpty(rp_s[i]) || rp_t[i] == null)
                {
                    //MessageBox.Show("存在违法匹配项或替换项！");
                    return str;
                }
            }
            string result = "";
            string substr = str;
            string rp = "";
            int len = 0;
        loop:
            // 如果存在匹配项则替换。
            for (int i = 0; i < t; i++)
            {
                rp = rp_s[i];
                len = rp.Length;
                if (str.StartsWith(rp))
                {
                    result += rp_t[i];
                    substr = str.Substring(len);
                    break;
                }
            }
            // 如果不存在匹配项则移位。
            if (substr == str)
            {
                result += str[0];
                substr = str.Substring(1);
            }
            str = substr;
            if (substr.Length != 0)
                goto loop;
            return result;
        }

        /// <summary>
        /// 设置IP地址、子网掩码、默认网关和首选DNS服务器。
        /// </summary>
        /// <param name="ip">IP地址。</param>
        /// <param name="submask">子网掩码。</param>
        /// <param name="getway">默认网关。</param>
        /// <param name="dns">首选DNS服务器。</param>
        /// <param name="netcard">网卡。</param>
        //public void SetIPAddress(
        //    string[] ip , string[] submask , string[] getway , string[] dns , string netcard)
        //{
        //    ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
        //    ManagementObjectCollection moc = wmi.GetInstances();
        //    ManagementBaseObject inPar = null;
        //    foreach (ManagementObject mo in moc)
        //    {
        //        if (!mo["Caption"].ToString().EndsWith(netcard))
        //            continue;
        //        //如果没有启用IP设置的网络设备则跳过。
        //        if (!(bool)mo["IPEnabled"])
        //            continue;
        //        //设置IP地址和子网掩码。
        //        if (ip != null && submask != null)
        //        {
        //            inPar = mo.GetMethodParameters("Enable");
        //            inPar["IPAddress"] = ip;
        //            inPar["SubnetMask"] = submask;
        //            mo.InvokeMethod("Enable" , inPar , null);
        //        }
        //        //设置默认网关。
        //        if (getway != null)
        //        {
        //            inPar = mo.GetMethodParameters("SetGateways");
        //            inPar["DefaultIPGateway"] = getway;
        //            mo.InvokeMethod("SetGateways" , inPar , null);
        //        }
        //        //设置首选DNS服务器。
        //        if (dns != null)
        //        {
        //            inPar = mo.GetMethodParameters("SetDNSServerSearchOrder");
        //            inPar["DNSServerSearchOrder"] = dns;
        //            mo.InvokeMethod("SetDNSServerSearchOrder" , inPar , null);
        //        }
        //    }
        //}

        /// <summary>
        /// 启用DHCP服务器（自动获取IP地址）。
        /// </summary>
        /// <param name="netcard">网卡。</param>
        //public void EnableDHCP(string netcard)
        //{
        //    ManagementClass wmi = new ManagementClass("Win32_NetworkAdapterConfiguration");
        //    ManagementObjectCollection moc = wmi.GetInstances();
        //    foreach (ManagementObject mo in moc)
        //    {
        //        if (!mo["Caption"].ToString().EndsWith(netcard)) continue;
        //        //如果没有启用IP设置的网络设备则跳过。
        //        if (!(bool)mo["IPEnabled"]) continue;
        //        //重置DNS为空。
        //        mo.InvokeMethod("SetDNSServerSearchOrder", null);
        //        //开启DHCP。
        //        mo.InvokeMethod("EnableDHCP", null);
        //    }
        //}

        #region 按索引的一半输出列表
        /// <summary>
        /// 按索引的一半输出列表。
        /// </summary>
        /// <param name="output">输出列表。</param>
        /// <param name="input">输入列表。</param>
        /// <param name="offset">偏移量。</param>
        /// <param name="count">输出长度。</param>
        private void OutputbyHalf(ArrayList output , ArrayList input ,
            int offset , int count)
        {
            if (count < 1)
                return;
            int m = count / 2;
            object item = input[m + offset];
            output.Add(item);
            OutputbyHalf(output , input , offset , m); //输出左半部分  
            OutputbyHalf(output , input , offset + m + 1 , count - m - 1); //输出右半部分  
        }

        /// <summary>
        /// 按索引的一半输出列表。
        /// </summary>
        /// <param name="input">输入列表。</param>
        /// <returns>输出列表。</returns>
        public ArrayList OutputbyHalf(ArrayList input)
        {
            ArrayList output = new ArrayList();
            OutputbyHalf(output , input , 0 , input.Count);
            return output;
        }
        #endregion

        #region 坐标格式转换
        /// <summary>
        /// 坐标格式转换。
        /// </summary>
        /// <param name="coor">坐标格式：112.23453（表示112度23分45.3秒）。</param>
        /// <returns>坐标格式：112.395916（表示112.395916度）。</returns>
        public double CoorFormatConvert1(string coor)
        {
            double sign = 1;
            if (double.Parse(coor) < 0)
                sign = -1;
            coor = Math.Abs(double.Parse(coor)).ToString();
            string[] temp = coor.Split('.');
            if (temp.Length > 1)
            {
                double value = double.Parse(temp[0]);
                if (temp[1].Length == 1)
                    value += double.Parse(temp[1]) / 6.0;
                if (temp[1].Length >= 2)
                    value += double.Parse(temp[1].Substring(0 , 2)) / 60.0;
                if (temp[1].Length >= 3)
                    value += double.Parse("0." + temp[1].Substring(2)) / 36.0;
                return value * sign;
            }
            else
                return double.Parse(coor) * sign;
        }

        /// <summary>
        /// 坐标格式转换。
        /// </summary>
        /// <param name="coor">坐标格式：112.395916（表示112.395916度）。</param>
        /// <returns>坐标格式：112.23453（表示112度23分45.3秒）。</returns>
        public double CoorFormatConvert2(double coor)
        {
            double du = (long)(coor);
            double fen = (long)((coor - du) * 60);
            double miao = (coor - du) * 3600 - fen * 60;
            // 防止溢出
            coor = du + fen / 100 + miao / 10000;
            if (((long)(coor * 10000) - (long)(coor * 100) * 100) >= 60)
                coor += 0.004;
            if (((long)(coor * 100) - (long)(coor) * 100) >= 60)
                coor += 0.4;
            return coor;
        }

        /// <summary>
        /// 坐标格式转换。
        /// </summary>
        /// <param name="coor">坐标格式：112.23453（表示112度23分45.3秒）。</param>
        /// <returns>坐标格式：112度23分45.3秒。</returns>
        public string CoorFormatConvert3(string coor)
        {
            string[] temp = coor.Split('.');
            coor = double.Parse(temp[0]) + "度";
            if (temp.Length > 1)
            {
                if (temp[1].Length == 1)
                    coor += temp[1] + "0分";
                if (temp[1].Length >= 2)
                    coor += temp[1].Substring(0 , 2) + "分";
                if (temp[1].Length >= 3)
                    coor +=
                        double.Parse("0." + temp[1].Substring(2)) * 100.0 + "秒";
            }
            return coor;
        }

        /// <summary>
        /// 坐标格式转换。
        /// </summary>
        /// <param name="coor">坐标格式：112度23分45.3秒。</param>
        /// <returns>坐标格式：112.23453（表示112度23分45.3秒）。</returns>
        public string CoorFormatConvert4(string coor)
        {
            string[] temp = coor.Split('度');
            double value = double.Parse(temp[0]);
            double sign = 1;
            if (value < 0)
                sign = -1;
            value = Math.Abs(value);
            if (temp[1].IndexOf('分') > -1)
            {
                temp = temp[1].Split('分');
                value += double.Parse(temp[0]) / 100;
                if (temp[1].IndexOf('秒') > -1)
                {
                    temp = temp[1].Split('秒');
                    value += double.Parse(temp[0]) / 10000;
                }
            }
            return (value * sign).ToString();
        }
        #endregion

        #region 图幅计算
        /// <summary>
        /// 根据经纬度坐标计算八种基本比例尺的旧图幅编号。
        /// </summary>
        /// <param name="l">经度（单位：秒）。</param>
        /// <param name="b">纬度（单位：秒）。</param>
        /// <param name="scale">比例尺（单位：万）</param>
        /// <returns>图幅编号。</returns>
        public string GetMapCodeOld(double l , double b , double scale)
        {
            l += 180 * 3600;
            // 判断南北半球
            string ns = b < 0 ? "S" : "N";
            b = Math.Abs(b);
            // 使坐标不在图幅线上
            double temp1 = l / 112.5;
            if ((long)(temp1) == temp1)
                l += 0.1;
            temp1 = b / 75;
            if ((long)(temp1) == temp1)
                b += 0.1;
            // 若坐标超出范围返回空
            if (l < 0 || l > 360 * 3600 || b > 60 * 3600)
                return null;
            Dictionary<double , string> mapCodeDic = new Dictionary<double , string>();
            // 100
            long temp2 = (long)(l / 21600);
            long temp3 = (long)(b / 14400);
            mapCodeDic[100] = ns + Convert.ToChar('A' + temp3) + '-' + (temp2 + 1);
            // 50
            l -= temp2 * 21600;
            b -= temp3 * 14400;
            temp2 = (l > 10800 ? 1 : 0) + (b > 7200 ? 0 : 2);
            mapCodeDic[50] = mapCodeDic[100] + '-' + Convert.ToChar('A' + temp2);
            // 25
            temp2 = (long)(l / 5400) + 1 + (long)((14400 - b) / 3600) * 4;
            mapCodeDic[25] = mapCodeDic[100] + "-[" + temp2 + ']';
            // 10
            temp2 = (long)(l / 1800) + 1 + (long)((14400 - b) / 1200) * 12;
            mapCodeDic[10] = mapCodeDic[100] + '-' + temp2;
            // 5
            l -= (long)(l / 1800) * 1800;
            b -= (long)(b / 1200) * 1200;
            temp2 = (l > 900 ? 1 : 0) + (b > 600 ? 0 : 2);
            mapCodeDic[5] = mapCodeDic[10] + '-' + Convert.ToChar('A' + temp2);
            // 2.5
            double l5 = l - (long)(l / 900) * 900;
            double b5 = b - (long)(b / 600) * 600;
            temp2 = (l5 > 450 ? 2 : 1) + (b5 > 300 ? 0 : 2);
            mapCodeDic[2.5] = mapCodeDic[5] + '-' + temp2;
            // 1
            temp2 = (long)(l / 225) + 1 + (long)((1200 - b) / 150) * 8;
            mapCodeDic[1] = mapCodeDic[10] + "-(" + temp2 + ')';
            // 0.5
            l -= (long)(l / 225) * 225;
            b -= (long)(b / 150) * 150;
            temp2 = (l > 112.5 ? 1 : 0) + (b > 75 ? 0 : 2);
            mapCodeDic[0.5] = mapCodeDic[1] + '-' + Convert.ToChar('a' + temp2);

            if (mapCodeDic.ContainsKey(scale))
                return mapCodeDic[scale];
            else
                return null;
        }

        /// <summary>
        /// 根据经纬度坐标计算八种基本比例尺的新图幅编号。
        /// </summary>
        /// <param name="l">经度（单位：秒）。</param>
        /// <param name="b">纬度（单位：秒）。</param>
        /// <param name="scale">比例尺（单位：万）</param>
        /// <returns>图幅编号。</returns>
        public string GetMapCodeNew(double l , double b , double scale)
        {
            l += 180 * 3600;
            // 判断南北半球
            string ns = b < 0 ? "S" : "N";
            b = Math.Abs(b);
            // 使坐标不在图幅线上
            double temp1 = l / 112.5;
            if ((long)(temp1) == temp1)
                l += 0.1;
            temp1 = b / 75;
            if ((long)(temp1) == temp1)
                b += 0.1;
            // 若坐标超出范围返回空
            if (l < 0 || l > 360 * 3600 || b > 60 * 3600)
                return null;
            Dictionary<double , string> mapCodeDic = new Dictionary<double , string>();
            // 100
            long temp2 = (long)(l / 21600);
            long temp3 = (long)(b / 14400);
            l -= temp2 * 21600;
            b -= temp3 * 14400;
            mapCodeDic[100] = ns + Convert.ToChar('A' + temp3) + (temp2 + 1);
            // 50
            temp2 = (long)((14400 - b) / 7200) + 1;
            temp3 = (long)(l / 10800) + 1;
            mapCodeDic[50] = mapCodeDic[100] + 'B' +
                (temp2 + 1000).ToString().Substring(1) + (temp3 + 1000).ToString().Substring(1);
            // 25
            temp2 = (long)((14400 - b) / 3600) + 1;
            temp3 = (long)(l / 5400) + 1;
            mapCodeDic[25] = mapCodeDic[100] + 'C' +
                (temp2 + 1000).ToString().Substring(1) + (temp3 + 1000).ToString().Substring(1);
            // 10
            temp2 = (long)((14400 - b) / 1200) + 1;
            temp3 = (long)(l / 1800) + 1;
            mapCodeDic[10] = mapCodeDic[100] + 'D' +
                (temp2 + 1000).ToString().Substring(1) + (temp3 + 1000).ToString().Substring(1);
            // 5
            temp2 = (long)((14400 - b) / 600) + 1;
            temp3 = (long)(l / 900) + 1;
            mapCodeDic[5] = mapCodeDic[100] + 'E' +
                (temp2 + 1000).ToString().Substring(1) + (temp3 + 1000).ToString().Substring(1);
            // 2.5
            temp2 = (long)((14400 - b) / 300) + 1;
            temp3 = (long)(l / 450) + 1;
            mapCodeDic[2.5] = mapCodeDic[100] + 'F' +
                (temp2 + 1000).ToString().Substring(1) + (temp3 + 1000).ToString().Substring(1);
            // 1
            temp2 = (long)((14400 - b) / 150) + 1;
            temp3 = (long)(l / 225) + 1;
            mapCodeDic[1] = mapCodeDic[100] + 'G' +
                (temp2 + 1000).ToString().Substring(1) + (temp3 + 1000).ToString().Substring(1);
            // 0.5
            temp2 = (long)((14400 - b) / 75) + 1;
            temp3 = (long)(l / 112.5) + 1;
            mapCodeDic[0.5] = mapCodeDic[100] + 'H' +
                (temp2 + 1000).ToString().Substring(1) + (temp3 + 1000).ToString().Substring(1);

            if (mapCodeDic.ContainsKey(scale))
                return mapCodeDic[scale];
            else
                return null;
        }

        /// <summary>
        /// 获取指定图幅编号的图幅左经度（单位：秒）。
        /// </summary>
        /// <param name="mapCode">图幅编号。</param>
        /// <returns>经度（单位：秒）。</returns>
        public double GetCoorLeft(string mapCode)
        {
            // 删除表示南北半球的首字符
            mapCode = mapCode.Substring(1);
            double coor = 0;
            if (mapCode.IndexOf('-') > -1)// 旧图幅编号
            {
                string[] temp = mapCode.Split('-');
                coor = (double.Parse(temp[1]) - 1) * 21600;// 100
                if (temp.Length > 2)
                {
                    if (temp[2][0] == 'B' || temp[2][0] == 'D')
                        coor += 10800;// 50
                    else if (temp[2][0] == '[')
                        coor += (int.Parse(temp[2].Trim("[]".ToCharArray())) - 1) % 4 * 5400;// 25
                    else if (char.IsDigit(temp[2][0]))
                    {
                        coor += (int.Parse(temp[2]) - 1) % 12 * 1800;// 10
                        if (temp.Length > 3)
                        {
                            if (char.IsLetter(temp[3][0]))
                            {
                                if (temp[3][0] == 'B' || temp[3][0] == 'D')
                                    coor += 900;// 5
                                if (temp.Length > 4 && int.Parse(temp[4]) % 2 == 0)
                                    coor += 450;// 2.5
                            }
                            else
                            {
                                coor += (int.Parse(temp[3].Trim("()".ToCharArray())) - 1) % 8 * 225;// 1
                                if (temp.Length > 4 && (temp[4][0] == 'b' || temp[4][0] == 'd'))
                                    coor += 112.5;// 0.5
                            }
                        }
                    }
                }
            }
            else// 新图幅编号
            {
                // 删除横行号
                mapCode = mapCode.Substring(1);
                string[] temp = mapCode.Split("BCDEFGH".ToCharArray());
                coor = (double.Parse(temp[0]) - 1) * 21600;// 100
                if (temp.Length > 1)
                {
                    if (mapCode.IndexOf('B') > -1)
                        coor += (int.Parse(temp[1].Substring(3)) - 1) * 10800;// 50
                    else if (mapCode.IndexOf('C') > -1)
                        coor += (int.Parse(temp[1].Substring(3)) - 1) * 5400;// 25
                    else if (mapCode.IndexOf('D') > -1)
                        coor += (int.Parse(temp[1].Substring(3)) - 1) * 1800;// 10
                    else if (mapCode.IndexOf('E') > -1)
                        coor += (int.Parse(temp[1].Substring(3)) - 1) * 900;// 5
                    else if (mapCode.IndexOf('F') > -1)
                        coor += (int.Parse(temp[1].Substring(3)) - 1) * 450;// 2.5
                    else if (mapCode.IndexOf('G') > -1)
                        coor += (int.Parse(temp[1].Substring(3)) - 1) * 225;// 1
                    else if (mapCode.IndexOf('H') > -1)
                        coor += (int.Parse(temp[1].Substring(3)) - 1) * 112.5;// 0.5
                }
            }
            return coor - 180 * 3600;
        }

        /// <summary>
        /// 获取指定图幅编号的图幅右经度（单位：秒）。
        /// </summary>
        /// <param name="mapCode">图幅编号。</param>
        /// <returns>经度（单位：秒）。</returns>
        public double GetCoorRight(string mapCode)
        {
            // 删除表示南北半球的首字符
            mapCode = mapCode.Substring(1);
            double coor = 0;
            if (mapCode.IndexOf('-') > -1)// 旧图幅编号
            {
                string[] temp = mapCode.Split('-');
                coor = (double.Parse(temp[1]) - 1) * 21600;
                if (temp.Length == 2)
                    coor += 21600;// 100
                else
                {
                    if (temp[2][0] == 'A' || temp[2][0] == 'C')
                        coor += 10800;// 50
                    else if (temp[2][0] == 'B' || temp[2][0] == 'D')
                        coor += 21600;// 50
                    else if (temp[2][0] == '[')
                        coor += ((int.Parse(temp[2].Trim("[]".ToCharArray())) - 1) % 4 + 1) * 5400;// 25
                    else if (char.IsDigit(temp[2][0]))
                    {
                        coor += (int.Parse(temp[2]) - 1) % 12 * 1800;
                        if (temp.Length == 3)
                            coor += 1800;// 10
                        else
                        {
                            if (char.IsLetter(temp[3][0]))
                            {
                                if (temp[3][0] == 'B' || temp[3][0] == 'D')
                                    coor += 900;// 5
                                if (temp.Length == 4)
                                    coor += 900;// 5
                                else
                                    coor += ((int.Parse(temp[4]) - 1) % 2 + 1) * 450;// 2.5
                            }
                            else
                            {
                                coor += (int.Parse(temp[3].Trim("()".ToCharArray())) - 1) % 8 * 225;// 1
                                if (temp.Length == 4)
                                    coor += 225;
                                else if (temp[4][0] == 'a' || temp[4][0] == 'c')
                                    coor += 112.5;// 0.5
                                else if (temp[4][0] == 'b' || temp[4][0] == 'd')
                                    coor += 225;// 0.5
                            }
                        }
                    }
                }
            }
            else// 新图幅编号
            {
                // 删除横行号
                mapCode = mapCode.Substring(1);
                string[] temp = mapCode.Split("BCDEFGH".ToCharArray());
                coor = (double.Parse(temp[0]) - 1) * 21600;
                if (temp.Length == 1)
                    coor += 21600;// 100
                else
                {
                    if (mapCode.IndexOf('B') > -1)
                        coor += int.Parse(temp[1].Substring(3)) * 10800;// 50
                    else if (mapCode.IndexOf('C') > -1)
                        coor += int.Parse(temp[1].Substring(3)) * 5400;// 25
                    else if (mapCode.IndexOf('D') > -1)
                        coor += int.Parse(temp[1].Substring(3)) * 1800;// 10
                    else if (mapCode.IndexOf('E') > -1)
                        coor += int.Parse(temp[1].Substring(3)) * 900;// 5
                    else if (mapCode.IndexOf('F') > -1)
                        coor += int.Parse(temp[1].Substring(3)) * 450;// 2.5
                    else if (mapCode.IndexOf('G') > -1)
                        coor += int.Parse(temp[1].Substring(3)) * 225;// 1
                    else if (mapCode.IndexOf('H') > -1)
                        coor += int.Parse(temp[1].Substring(3)) * 112.5;// 0.5
                }
            }
            return coor - 180 * 3600;
        }

        /// <summary>
        /// 获取指定图幅编号的图幅下纬度（单位：秒）。
        /// </summary>
        /// <param name="mapCode">图幅编号。</param>
        /// <returns>纬度（单位：秒）。</returns>
        public double GetCoorBottom(string mapCode)
        {
            // 获取南北半球
            double sign = 1;
            if (mapCode.StartsWith("S"))
                sign = -1;
            // 删除表示南北半球的首字符
            mapCode = mapCode.Substring(1);
            double coor = 0;
            if (mapCode.IndexOf('-') > -1)// 旧图幅编号
            {
                string[] temp = mapCode.Split('-');
                coor = Convert.ToDouble(temp[0][0] - 'A') * 14400;// 100
                if (temp.Length > 2)
                {
                    if (temp[2][0] == 'A' || temp[2][0] == 'B')
                        coor += 7200;// 50
                    else if (temp[2][0] == '[')
                        coor += (3 - (int.Parse(temp[2].Trim("[]".ToCharArray())) - 1) / 4) * 3600;// 25
                    else if (char.IsDigit(temp[2][0]))
                    {
                        coor += (11 - (int.Parse(temp[2]) - 1) / 12) * 1200;// 10
                        if (temp.Length > 3)
                        {
                            if (char.IsLetter(temp[3][0]))
                            {
                                if (temp[3][0] == 'A' || temp[3][0] == 'B')
                                    coor += 600;// 5
                                if (temp.Length > 4 && int.Parse(temp[4]) < 3)
                                    coor += 300;// 2.5
                            }
                            else
                            {
                                coor += (7 - (int.Parse(temp[3].Trim("()".ToCharArray())) - 1) / 8) * 150;// 1
                                if (temp.Length > 4 && (temp[4][0] == 'a' || temp[4][0] == 'b'))
                                    coor += 75;// 0.5
                            }
                        }
                    }
                }
            }
            else// 新图幅编号
            {
                coor = Convert.ToDouble(mapCode[0] - 'A') * 14400;// 100
                // 删除横行号
                mapCode = mapCode.Substring(1);
                string[] temp = mapCode.Split("BCDEFGH".ToCharArray());
                if (temp.Length > 1)
                {
                    if (mapCode.IndexOf('B') > -1)
                        coor += (2 - int.Parse(temp[1].Substring(0 , 3))) * 7200;// 50
                    else if (mapCode.IndexOf('C') > -1)
                        coor += (4 - int.Parse(temp[1].Substring(0 , 3))) * 3600;// 25
                    else if (mapCode.IndexOf('D') > -1)
                        coor += (12 - int.Parse(temp[1].Substring(0 , 3))) * 1200;// 10
                    else if (mapCode.IndexOf('E') > -1)
                        coor += (24 - int.Parse(temp[1].Substring(0 , 3))) * 600;// 5
                    else if (mapCode.IndexOf('F') > -1)
                        coor += (48 - int.Parse(temp[1].Substring(0 , 3))) * 300;// 2.5
                    else if (mapCode.IndexOf('G') > -1)
                        coor += (96 - int.Parse(temp[1].Substring(0 , 3))) * 150;// 1
                    else if (mapCode.IndexOf('H') > -1)
                        coor += (192 - int.Parse(temp[1].Substring(0 , 3))) * 75;// 0.5
                }
            }
            return coor * sign;
        }

        /// <summary>
        /// 获取指定图幅编号的图幅上纬度（单位：秒）。
        /// </summary>
        /// <param name="mapCode">图幅编号。</param>
        /// <returns>纬度（单位：秒）。</returns>
        public double GetCoorTop(string mapCode)
        {
            // 获取南北半球
            double sign = 1;
            if (mapCode.StartsWith("S"))
                sign = -1;
            // 删除表示南北半球的首字符
            mapCode = mapCode.Substring(1);
            double coor = 0;
            if (mapCode.IndexOf('-') > -1)// 旧图幅编号
            {
                string[] temp = mapCode.Split('-');
                coor = Convert.ToDouble(temp[0][0] - 'A') * 14400;
                if (temp.Length == 2)
                    coor += 14400;// 100
                else
                {
                    if (temp[2][0] == 'A' || temp[2][0] == 'B')
                        coor += 14400;// 50
                    else if (temp[2][0] == 'C' || temp[2][0] == 'D')
                        coor += 7200;// 50
                    else if (temp[2][0] == '[')
                        coor += (4 - (int.Parse(temp[2].Trim("[]".ToCharArray())) - 1) / 4) * 3600;// 25
                    else if (char.IsDigit(temp[2][0]))
                    {
                        coor += (11 - (int.Parse(temp[2]) - 1) / 12) * 1200;
                        if (temp.Length == 3)
                            coor += 1200;// 10
                        else
                        {
                            if (char.IsLetter(temp[3][0]))
                            {
                                if (temp[3][0] == 'A' || temp[3][0] == 'B')
                                    coor += 600;// 5
                                if (temp.Length == 4)
                                    coor += 600;// 5
                                else
                                    coor += (2 - (int.Parse(temp[4]) - 1) / 2) * 300;// 2.5
                            }
                            else
                            {
                                coor += (7 - (int.Parse(temp[3].Trim("()".ToCharArray())) - 1) / 8) * 150;// 1
                                if (temp.Length == 4)
                                    coor += 150;
                                else if (temp[4][0] == 'a' || temp[4][0] == 'b')
                                    coor += 150;// 0.5
                                else if (temp[4][0] == 'c' || temp[4][0] == 'd')
                                    coor += 75;// 0.5
                            }
                        }
                    }
                }
            }
            else// 新图幅编号
            {
                coor = Convert.ToDouble(mapCode[0] - 'A') * 14400;// 100
                // 删除横行号
                mapCode = mapCode.Substring(1);
                string[] temp = mapCode.Split("BCDEFGH".ToCharArray());
                if (temp.Length == 1)
                    coor += 14400;
                else
                {
                    if (mapCode.IndexOf('B') > -1)
                        coor += (3 - int.Parse(temp[1].Substring(0 , 3))) * 7200;// 50
                    else if (mapCode.IndexOf('C') > -1)
                        coor += (5 - int.Parse(temp[1].Substring(0 , 3))) * 3600;// 25
                    else if (mapCode.IndexOf('D') > -1)
                        coor += (13 - int.Parse(temp[1].Substring(0 , 3))) * 1200;// 10
                    else if (mapCode.IndexOf('E') > -1)
                        coor += (25 - int.Parse(temp[1].Substring(0 , 3))) * 600;// 5
                    else if (mapCode.IndexOf('F') > -1)
                        coor += (49 - int.Parse(temp[1].Substring(0 , 3))) * 300;// 2.5
                    else if (mapCode.IndexOf('G') > -1)
                        coor += (97 - int.Parse(temp[1].Substring(0 , 3))) * 150;// 1
                    else if (mapCode.IndexOf('H') > -1)
                        coor += (193 - int.Parse(temp[1].Substring(0 , 3))) * 75;// 0.5
                }
            }
            return coor * sign;
        }
        #endregion

        

        #region 计算编辑距离
        /// <summary>
        /// 莱文斯坦距离（Levenshtein Distance）。
        /// </summary>
        /// <param name="source">源串。</param>
        /// <param name="target">目标串。</param>
        /// <param name="similarity">输出：相似度，值在0～1。</param>
        /// <param name="isCaseSensitive">是否大小写敏感。</param>
        /// <returns>源串和目标串之间的编辑距离。</returns>
        public int LevenshteinDistance(string source ,
            string target , out double similarity , bool isCaseSensitive)
        {
            if (string.IsNullOrEmpty(source))
            {
                if (string.IsNullOrEmpty(target))
                {
                    similarity = 1;
                    return 0;
                }
                else
                {
                    similarity = 0;
                    return target.Length;
                }
            }
            else if (string.IsNullOrEmpty(target))
            {
                similarity = 0;
                return source.Length;
            }

            string From , To;
            if (isCaseSensitive)
            {   // 大小写敏感
                From = source;
                To = target;
            }
            else
            {   // 大小写无关
                From = source.ToLower();
                To = target.ToLower();
            }

            // 初始化
            int m = From.Length;
            int n = To.Length;
            int[,] H = new int[m + 1 , n + 1];
            for (int i = 0; i <= m; i++)
                H[i , 0] = i;  // 注意：初始化[0,0]
            for (int j = 1; j <= n; j++)
                H[0 , j] = j;

            // 迭代
            for (int i = 1; i <= m; i++)
            {
                char SI = From[i - 1];
                for (int j = 1; j <= n; j++)
                {   // 删除（deletion） 插入（insertion） 替换（substitution）
                    if (SI == To[j - 1])
                        H[i , j] = H[i - 1 , j - 1];
                    else
                        H[i , j] = Math.Min(H[i - 1 , j - 1] , Math.Min(H[i - 1 , j] , H[i , j - 1])) + 1;
                }
            }

            // 计算相似度（此相似度未必合理）
            int MaxLength = Math.Max(m , n);   // 两字符串的最大长度
            similarity = ((double)(MaxLength - H[m , n])) / MaxLength;

            return H[m , n];    // 编辑距离
        }

        /// <summary>
        /// 受限的Damerau-Levenshtein Distance（只允许相邻字符交换）。
        /// </summary>
        /// <param name="source">源串。</param>
        /// <param name="target">目标串。</param>
        /// <param name="similarity">输出：相似度，值在0～1。</param>
        /// <param name="isCaseSensitive">是否大小写敏感。</param>
        /// <returns>源串和目标串之间的编辑距离。</returns>
        public int OptimalStringAlignmentDistance(string source ,
            string target , out double similarity , bool isCaseSensitive)
        {
            if (string.IsNullOrEmpty(source))
            {
                if (string.IsNullOrEmpty(target))
                {
                    similarity = 1;
                    return 0;
                }
                else
                {
                    similarity = 0;
                    return target.Length;
                }
            }
            else if (string.IsNullOrEmpty(target))
            {
                similarity = 0;
                return source.Length;
            }

            string From , To;
            if (isCaseSensitive)
            {   // 大小写敏感
                From = source;
                To = target;
            }
            else
            {   // 大小写无关
                From = source.ToLower();
                To = target.ToLower();
            }

            // 初始化
            int m = From.Length;
            int n = To.Length;
            int[,] H = new int[m + 1 , n + 1];
            for (int i = 0; i <= m; i++)
                H[i , 0] = i;  // 注意：初始化[0,0]
            for (int j = 1; j <= n; j++)
                H[0 , j] = j;

            // 迭代
            for (int i = 1; i <= m; i++)
            {
                char SI = From[i - 1];
                for (int j = 1; j <= n; j++)
                {   // 删除（deletion） 插入（insertion） 替换（substitution）
                    char DJ = To[j - 1];
                    if (SI == DJ)
                        H[i , j] = H[i - 1 , j - 1];
                    else
                        H[i , j] = Math.Min(H[i - 1 , j - 1] , Math.Min(H[i - 1 , j] , H[i , j - 1])) + 1;

                    if (i > 1 && j > 1)
                    {   // 交换相邻字符（transposition of two adjacent characters）
                        if (SI == To[j - 2] && DJ == From[i - 2])
                        {
                            H[i , j] = Math.Min(H[i , j] , H[i - 2 , j - 2] + 1);
                        }
                    }
                }
            }

            // 计算相似度（此相似度未必合理）
            int MaxLength = Math.Max(m , n);   // 两字符串的最大长度
            similarity = ((double)(MaxLength - H[m , n])) / MaxLength;

            return H[m , n];    // 编辑距离
        }

        /// <summary>
        /// 不受限的Damerau-Levenshtein Distance（允许交换字符间的删除插入操作）。
        /// </summary>
        /// <param name="source">源串。</param>
        /// <param name="target">目标串。</param>
        /// <param name="similarity">输出：相似度，值在0～1。</param>
        /// <param name="isCaseSensitive">是否大小写敏感。</param>
        /// <returns>源串和目标串之间的编辑距离。</returns>
        public int DamerauLevenshteinDistance(string source ,
            string target , out double similarity , bool isCaseSensitive)
        {
            if (string.IsNullOrEmpty(source))
            {
                if (string.IsNullOrEmpty(target))
                {
                    similarity = 1;
                    return 0;
                }
                else
                {
                    similarity = 0;
                    return target.Length;
                }
            }
            else if (string.IsNullOrEmpty(target))
            {
                similarity = 0;
                return source.Length;
            }

            string From , To;
            if (isCaseSensitive)
            {   // 大小写敏感
                From = source;
                To = target;
            }
            else
            {   // 大小写无关
                From = source.ToLower();
                To = target.ToLower();
            }

            // 初始化
            int m = From.Length;
            int n = To.Length;
            int[,] H = new int[m + 2 , n + 2];

            int INF = m + n;
            H[0 , 0] = INF;
            for (int i = 0; i <= m; i++)
            {
                H[i + 1 , 1] = i;
                H[i + 1 , 0] = INF;
            }
            for (int j = 0; j <= n; j++)
            {
                H[1 , j + 1] = j;
                H[0 , j + 1] = INF;
            }

            // 对维基百科中给出ActionScript代码优化，去掉参数C，可以更好地适合各国语言
            SortedDictionary<char , int> sd = new SortedDictionary<char , int>();
            foreach (char Letter in (From + To))
            {
                if (!sd.ContainsKey(Letter))
                    sd.Add(Letter , 0);
            }

            // 迭代
            for (int i = 1; i <= m; i++)
            {
                int DB = 0;
                for (int j = 1; j <= n; j++)
                {
                    int i1 = sd[To[j - 1]];   // 定位字符To[j-1]在源串From[0:i-2]中的最后一次索引
                    int j1 = DB;              // 定位字符From[i-1]在目标串To[0:j-2]中的最后一次索引

                    // 删除（deletion） 插入（insertion） 替换（substitution）
                    if (From[i - 1] == To[j - 1])
                    {
                        H[i + 1 , j + 1] = H[i , j];
                        DB = j;
                    }
                    else
                    {
                        H[i + 1 , j + 1] = Math.Min(H[i , j] , Math.Min(H[i + 1 , j] , H[i , j + 1])) + 1;
                    }

                    // transposition of two adjacent characters
                    // 将源串i1-1到i-1内的字符删除，然后交换i1-1和i-1的字符，再加上目标串j1-1到j-1内的字符
                    H[i + 1 , j + 1] = Math.Min(H[i + 1 , j + 1] , H[i1 , j1] + (i - i1 - 1) + 1 + (j - j1 - 1));
                }

                sd[From[i - 1]] = i;
            }

            // 计算相似度（此相似度未必合理）
            int MaxLength = Math.Max(m , n);   // 两字符串的最大长度
            similarity = ((double)(MaxLength - H[m + 1 , n + 1])) / MaxLength;

            return H[m + 1 , n + 1];    // 编辑距离
        }

        /// <summary>
        /// 不受限的Damerau-Levenshtein Distance（允许交换字符间的删除插入操作）。
        /// 更好理解的代码。
        /// </summary>
        /// <param name="source">源串。</param>
        /// <param name="target">目标串。</param>
        /// <param name="similarity">输出：相似度，值在0～1。</param>
        /// <param name="isCaseSensitive">是否大小写敏感。</param>
        /// <returns>源串和目标串之间的编辑距离。</returns>
        public int EZDamerauLevenshteinDistance(string source ,
            string target , out double similarity , bool isCaseSensitive)
        {
            if (string.IsNullOrEmpty(source))
            {
                if (string.IsNullOrEmpty(target))
                {
                    similarity = 1;
                    return 0;
                }
                else
                {
                    similarity = 0;
                    return target.Length;
                }
            }
            else if (string.IsNullOrEmpty(target))
            {
                similarity = 0;
                return source.Length;
            }

            string From , To;
            if (isCaseSensitive)
            {   // 大小写敏感
                From = source;
                To = target;
            }
            else
            {   // 大小写无关
                From = source.ToLower();
                To = target.ToLower();
            }

            // 初始化
            int m = From.Length;
            int n = To.Length;
            int[,] H = new int[m + 1 , n + 1];
            for (int i = 0; i <= m; i++)
                H[i , 0] = i;  // 注意：初始化[0,0]
            for (int j = 1; j <= n; j++)
                H[0 , j] = j;

            // 迭代
            for (int i = 1; i <= m; i++)
            {
                char SI = From[i - 1];
                for (int j = 1; j <= n; j++)
                {   // 删除（deletion） 插入（insertion） 替换（substitution）
                    char DJ = To[j - 1];
                    if (SI == DJ)
                        H[i , j] = H[i - 1 , j - 1];
                    else
                        H[i , j] = Math.Min(H[i - 1 , j - 1] , Math.Min(H[i - 1 , j] , H[i , j - 1])) + 1;

                    if (i > 1 && j > 1)
                    {   // 交换相邻字符（transposition of two adjacent characters）
                        int i1 = From.LastIndexOf(DJ , i - 2 , i - 1);
                        if (i1 != -1)
                        {
                            int j1 = To.LastIndexOf(SI , j - 2 , j - 1);
                            if (j1 != -1)
                            {   // 将源串i1到i-1内的字符删除，然后交换i1和i-1的字符，再加上目标串j1到j-1内的字符
                                H[i , j] = Math.Min(H[i , j] , H[i1 , j1] + (i - i1 - 2) + 1 + (j - j1 - 2));
                            }
                        }
                    }
                }
            }

            // 计算相似度（此相似度未必合理）
            int MaxLength = Math.Max(m , n);   // 两字符串的最大长度
            similarity = ((double)(MaxLength - H[m , n])) / MaxLength;

            return H[m , n];    // 编辑距离
        }
        #endregion

        //using System.Web.Security; 

        #region 加解密
        /// <summary>
        /// 用DES算法以UTF8编码将字符串加密并保存到文件中。
        /// </summary>
        /// <param name="text">需要加密的字符串。</param>
        /// <param name="file">文件名。</param>
        /// <param name="password">密码。</param>
        public void DESEncryptString(string text , string file , string password)
        {
            using (FileStream fs = new FileStream(
                file , FileMode.Create , FileAccess.Write))
            {
                using (DESCryptoServiceProvider DES = new DESCryptoServiceProvider())
                {
                    DES.Key = Encoding.UTF8.GetBytes(password);
                    DES.IV = Encoding.UTF8.GetBytes(password);
                    ICryptoTransform transform = DES.CreateEncryptor();
                    using (CryptoStream cs = new CryptoStream(fs , transform , CryptoStreamMode.Write))
                    {
                        byte[] data = Encoding.UTF8.GetBytes(text);
                        cs.Write(data , 0 , data.Length);
                        cs.Close();
                    }
                }
                fs.Close();
            }
        }

        /// <summary>
        /// 用DES算法以UTF8编码解密文本文件。
        /// </summary>
        /// <param name="file">文件名。</param>
        /// <param name="password">密码。</param>
        /// <returns>字符串。</returns>
        public string DESDecryptFile(string file , string password)
        {
            using (FileStream fs = new FileStream(file , FileMode.Open , FileAccess.Read))
            {
                using (DESCryptoServiceProvider DES = new DESCryptoServiceProvider())
                {
                    DES.Key = Encoding.UTF8.GetBytes(password);
                    DES.IV = Encoding.UTF8.GetBytes(password);
                    ICryptoTransform transform = DES.CreateDecryptor();
                    using (CryptoStream cs = new CryptoStream(fs , transform , CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs , Encoding.UTF8))
                        {
                            return sr.ReadToEnd();
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 用DES算法以UTF8编码解密文本文件。
        /// </summary>
        /// <param name="file">文件名。</param>
        /// <param name="password">密码。</param>
        /// <returns>文件流阅读器。</returns>
        public StreamReader DESFileDecrypt(string file , string password)
        {
            FileStream fs = new FileStream(file , FileMode.Open , FileAccess.Read);
            DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
            DES.Key = Encoding.UTF8.GetBytes(password);
            DES.IV = Encoding.UTF8.GetBytes(password);
            ICryptoTransform transform = DES.CreateDecryptor();
            CryptoStream cs = new CryptoStream(fs , transform , CryptoStreamMode.Read);
            return new StreamReader(cs , Encoding.UTF8);
        }

        /// <summary>
        /// 更改对称加密key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool symmetric_key(string key)
        {
            symmetric_encrypto.key = key;
            return true;
        }

        /// <summary>    
        /// 加密方法    
        /// </summary>    
        /// <param name="Source">待加密的串</param>    
        /// <returns>经过加密的串</returns>    
        public string symmetric_encrypto_对称加密加密(string source)
        {
            return symmetric_encrypto.Encrypto(source);
        }

        /// <summary>    
        /// 解密方法    
        /// </summary>    
        /// <param name="Source">待解密的串</param>    
        /// <returns>经过解密的串</returns>    
        public string symmetric_decrypto_对称加密解密(string source)
        {
            return symmetric_encrypto.Decrypto(source);
        }
        #endregion


        /// <summary> 
        /// SHA1加密字符串 
        /// </summary> 
        /// <param name="source">源字符串</param> 
        /// <returns>加密后的字符串</returns> 
        //public string SHA1(string source)
        //{
        //    return FormsAuthentication.HashPasswordForStoringInConfigFile(source , "SHA1");
        //} 
        //using System.IO; 
        //using System.Security.Cryptography; 

        /// <summary>
        /// 对称加密
        /// </summary>
        public SymmetricMethod symmetric_encrypto = new SymmetricMethod();
       

        public class SymmetricMethod
        {
            /// <summary>    
            /// 对称加密类的构造函数    
            /// </summary>    
            public SymmetricMethod()
            {
                mobjCryptoService = new RijndaelManaged();
                key = "sartfasfdsfwa";
            }
            public string key
            {
                set
                {
                    _key = value;
                }
                get
                {
                    return _key;
                }                
            }            
           
            /// <summary>    
            /// 加密方法    
            /// </summary>    
            /// <param name="Source">待加密的串</param>    
            /// <returns>经过加密的串</returns>    
            public string Encrypto(string Source)
            {
                byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
                MemoryStream ms = new MemoryStream();
                mobjCryptoService.Key = GetLegalKey();
                mobjCryptoService.IV = GetLegalIV();
                ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
                CryptoStream cs = new CryptoStream(ms , encrypto , CryptoStreamMode.Write);
                cs.Write(bytIn , 0 , bytIn.Length);
                cs.FlushFinalBlock();
                ms.Close();
                byte[] bytOut = ms.ToArray();
                return Convert.ToBase64String(bytOut);
            }

            /// <summary>    
            /// 解密方法    
            /// </summary>    
            /// <param name="Source">待解密的串</param>    
            /// <returns>经过解密的串</returns>    
            public string Decrypto(string Source)
            {
                byte[] bytIn = Convert.FromBase64String(Source);
                MemoryStream ms = new MemoryStream(bytIn , 0 , bytIn.Length);
                mobjCryptoService.Key = GetLegalKey();
                mobjCryptoService.IV = GetLegalIV();
                ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
                CryptoStream cs = new CryptoStream(ms , encrypto , CryptoStreamMode.Read);
                StreamReader sr = new StreamReader(cs);
                return sr.ReadToEnd();
            }

            private SymmetricAlgorithm mobjCryptoService;
            private string _key;

            /// <summary>    
            /// 获得密钥    
            /// </summary>    
            /// <returns>密钥</returns>    
            private byte[] GetLegalKey()
            {
                string sTemp = key;
                mobjCryptoService.GenerateKey();
                byte[] bytTemp = mobjCryptoService.Key;
                int KeyLength = bytTemp.Length;
                if (sTemp.Length > KeyLength)
                    sTemp = sTemp.Substring(0 , KeyLength);
                else if (sTemp.Length < KeyLength)
                    sTemp = sTemp.PadRight(KeyLength , ' ');
                return ASCIIEncoding.ASCII.GetBytes(sTemp);
            }
            /// <summary>    
            /// 获得初始向量IV    
            /// </summary>    
            /// <returns>初试向量IV</returns>    
            private byte[] GetLegalIV()
            {
                string sTemp = "E4ghj*g7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
                mobjCryptoService.GenerateIV();
                byte[] bytTemp = mobjCryptoService.IV;
                int IVLength = bytTemp.Length;
                if (sTemp.Length > IVLength)
                    sTemp = sTemp.Substring(0 , IVLength);
                else if (sTemp.Length < IVLength)
                    sTemp = sTemp.PadRight(IVLength , ' ');
                return ASCIIEncoding.ASCII.GetBytes(sTemp);
            }
        }

        public class jm_加密
        {
            ///需要 using System.IO;
            public string key = "林德熙";
            private jm_加密()
            {
                f_文件地址 = "E:\\【编北】\\程 序\\honker\\ce\\t\\加密\\jia\\data.data";
                _temp_临时字符串长 = 1024;
                //file = new FileStream(f_文件地址 , FileMode.OpenOrCreate);
            }
            public jm_加密(string file_加密的文件 , int 密钥_大于512)
            {
                密钥_大于512 = 1024;
                _temp_临时字符串长 = 密钥_大于512;

                f_文件地址 = file_加密的文件;
                //file = new FileStream(f_文件地址 , FileMode.OpenOrCreate);
            }
            private int r_随机数
            {
                set
                {
                    _随机数 = new Random(value);
                }
                get
                {
                    return _随机数.Next(2) == 0 ? _随机数.Next(19968 , 40864) : _随机数.Next(33 , 126);
                }
            }
            public static jm_加密 g_获得类()
            {
                return _加密;
            }
            public static jm_加密 g_获得类(string file_加密的文件)
            {
                _加密 = new jm_加密(file_加密的文件 , 1024);
                return _加密;
            }

            ~jm_加密()
            {


            }

            public string encryption(string str)
            {
                Random ra = new Random();
                char[] strB = str.ToCharArray();
                char[] m = key.ToCharArray();
                char[] s = new char[100000];
                int i;
                int j;
                int buf;
                for (i = 0; i < 100000; i++)
                {
                    s[i] = (char)0;
                }
                for (i = 0 , j = 0; i < strB.Length; i++)
                {
                    if (j == m.Length)
                        j = 0;
                    buf = strB[i];
                    buf += i + m[j];
                    int t;
                    t = 0;
                    while (s[m[j + t]] != 0)
                    {
                        t++;
                    }
                    s[m[j + t]] = (char)buf;
                    //while(s[m[j]]!=0)
                    //{
                    //  m[j]++;
                    //}
                }
                for (i = 0; i < 100000; i++)
                {
                    if (s[i] == 0)
                    {
                        s[i] = (char)ra.Next(50000);
                    }
                }

                return s.ToString();

            }

            public string decryption(string str)
            {
                char[] strB = str.ToCharArray();
                char[] buf = new char[100000];
                char[] m;
                m = key.ToCharArray();
                int i;
                int j;
                int t;
                i = 0;
                j = 0;
                t = 0;
                for (i = 0; i < 100000; i++)
                {
                    if (j == m.Length)
                        j = 0;
                    while (strB[m[j + t]] != 0)
                    {
                        t++;
                    }
                    buf[i] = strB[m[j + t]];
                    buf[i] = (char)((int)buf[i] - i - m[j]);
                    strB[m[j + t]] = (char)0;
                }

                return buf.ToString();
                //return null;
            }


            /// <summary>
            /// 写加密文件
            /// </summary>
            ///<param name="str">函数要写入文件内容</param>
            /// <returns>如果写成功返回true</returns>
            public bool x_写文件(string str)
            {
                //byte[] buf = Encoding.UTF8.GetBytes(str);
                //file = new FileStream(f_文件地址 , FileMode.Create);
                //file.Write(buf,0,buf.Length);
                //file.Flush();
                //file.Close();
                FileStream xiaFile = new FileStream(f_文件地址 , FileMode.Create);
                //byte[] buf = Encoding.UTF8.GetBytes(str); //Encoding.Default.GetBytes(str);  
                byte[] buf = Encoding.Unicode.GetBytes(str);
                xiaFile.Write(buf , 0 , buf.Length);
                xiaFile.Flush();
                xiaFile.Close();

                //file = new StreamReader(f_文件地址, Encoding.Default); 
                return true;
            }

            /// <summary>
            /// 读文件
            /// </summary>
            /// <param name="str">读文件内容保存到str</param>
            /// <returns>读文件成功返回true</returns>
            public bool d_读文件(out string str)
            {
                FileInfo fi = new FileInfo(f_文件地址);
                long len = fi.Length;

                FileStream fs = new FileStream(f_文件地址 , FileMode.Open);
                //file = new FileStream(f_文件地址 , FileMode.Open);
                byte[] buffer = new byte[len];
                //file.Read(buffer , 0 , (int)len);
                //file.Flush();
                //file.Close();
                fs.Read(buffer , 0 , (int)len);
                fs.Close();
                //str = Encoding.UTF8.GetString(buffer);
                str = Encoding.Unicode.GetString(buffer);
                //str = Encoding.Default.GetString(buffer);
                return true;
            }
            public string jm_加密字符串(string str)
            {
                char[] temp_str = new char[_temp_临时字符串长];
                int i , l , key_l;
                str += "结束";
                str.PadRight(_temp_临时字符串长);
                for (i = 0; i < _temp_临时字符串长; i++)
                {
                    temp_str[i] = Convert.ToChar(0);
                }
                key_l = 0;
                for (i = 0; i < str.Length; i++)
                {
                    l = Convert.ToInt32(key[key_l]);
                    l = l % _temp_临时字符串长;
                    while (temp_str[l] != Convert.ToChar(0))
                    {
                        l++;
                        if (l >= _temp_临时字符串长)
                        {
                            l = 0;
                        }
                    }
                    temp_str[l] = (char)(str[i]);//+key[key_l]);
                    key_l++;
                    if (key_l == key.Length)
                    {
                        key_l = 0;
                    }
                }
                for (i = 0; i < _temp_临时字符串长; i++)
                {
                    if (temp_str[i] == Convert.ToChar(0))
                    {
                        temp_str[i] = Convert.ToChar(r_随机数); //% 1000+1);
                    }
                }
                string s = new string(temp_str);
                return s;
                //return null;
            }
            public string jmz_解密字符串(string str)
            {
                StringBuilder s = new StringBuilder();
                char[] jie = str.ToCharArray();
                int l , key_l;
                bool 完成;
                完成 = false;
                l = 0;
                key_l = 0;
                if (jie.Length < _temp_临时字符串长 - 1)
                {
                    return "错" + jie.Length.ToString();
                }
                while (完成 == false)
                {
                    l = Convert.ToInt32(key[key_l]);
                    l = l % _temp_临时字符串长;
                    while (jie[l] == Convert.ToChar(0))
                    {
                        l++;
                        if (l >= _temp_临时字符串长)
                        {
                            完成 = true;
                            break;
                        }
                    }
                    if (完成)
                    {
                        break;
                    }
                    s.Append((char)(jie[l]));//-key[key_l]));
                    jie[l] = Convert.ToChar(0);
                    key_l++;
                    if (key_l == key.Length)
                    {
                        key_l = 0;
                    }
                }
                string temp_str = s.ToString();
                int temp_l = temp_str.LastIndexOf("结束");
                if (temp_l > 0)
                {
                    return temp_str.Substring(0 , temp_l);
                }
                else
                {
                    return null;
                }
            }

            private int _temp_临时字符串长;
            private static jm_加密 _加密 = new jm_加密();
            private Random _随机数 = new Random();
            //加密文件的路径
            private string f_文件地址;
            //private FileStream file;

        }    
    }

    public class 汉字转拼音
    {
        /**/
        /// <summary>
        /// 包含字符 ASC 码的整形数组。
        /// </summary>
        private static int[] pv = new int[] { -20319 , -20317 , -20304 , -20295 , -20292 , -20283 , -20265 , -20257 , -20242 , -20230 , -20051 , -20036 , -20032 , -20026 , -20002 , -19990 , -19986 , -19982 , -19976 , -19805 , -19784 , -19775 , -19774 , -19763 , -19756 , -19751 , -19746 , -19741 , -19739 , -19728 , -19725 , -19715 , -19540 , -19531 , -19525 , -19515 , -19500 , -19484 , -19479 , -19467 , -19289 , -19288 , -19281 , -19275 , -19270 , -19263 , -19261 , -19249 , -19243 , -19242 , -19238 , -19235 , -19227 , -19224 , -19218 , -19212 , -19038 , -19023 , -19018 , -19006 , -19003 , -18996 , -18977 , -18961 , -18952 , -18783 , -18774 , -18773 , -18763 , -18756 , -18741 , -18735 , -18731 , -18722 , -18710 , -18697 , -18696 , -18526 , -18518 , -18501 , -18490 , -18478 , -18463 , -18448 , -18447 , -18446 , -18239 , -18237 , -18231 , -18220 , -18211 , -18201 , -18184 , -18183 , -18181 , -18012 , -17997 , -17988 , -17970 , -17964 , -17961 , -17950 , -17947 , -17931 , -17928 , -17922 , -17759 , -17752 , -17733 , -17730 , -17721 , -17703 , -17701 , -17697 , -17692 , -17683 , -17676 , -17496 , -17487 , -17482 , -17468 , -17454 , -17433 , -17427 , -17417 , -17202 , -17185 , -16983 , -16970 , -16942 , -16915 , -16733 , -16708 , -16706 , -16689 , -16664 , -16657 , -16647 , -16474 , -16470 , -16465 , -16459 , -16452 , -16448 , -16433 , -16429 , -16427 , -16423 , -16419 , -16412 , -16407 , -16403 , -16401 , -16393 , -16220 , -16216 , -16212 , -16205 , -16202 , -16187 , -16180 , -16171 , -16169 , -16158 , -16155 , -15959 , -15958 , -15944 , -15933 , -15920 , -15915 , -15903 , -15889 , -15878 , -15707 , -15701 , -15681 , -15667 , -15661 , -15659 , -15652 , -15640 , -15631 , -15625 , -15454 , -15448 , -15436 , -15435 , -15419 , -15416 , -15408 , -15394 , -15385 , -15377 , -15375 , -15369 , -15363 , -15362 , -15183 , -15180 , -15165 , -15158 , -15153 , -15150 , -15149 , -15144 , -15143 , -15141 , -15140 , -15139 , -15128 , -15121 , -15119 , -15117 , -15110 , -15109 , -14941 , -14937 , -14933 , -14930 , -14929 , -14928 , -14926 , -14922 , -14921 , -14914 , -14908 , -14902 , -14894 , -14889 , -14882 , -14873 , -14871 , -14857 , -14678 , -14674 , -14670 , -14668 , -14663 , -14654 , -14645 , -14630 , -14594 , -14429 , -14407 , -14399 , -14384 , -14379 , -14368 , -14355 , -14353 , -14345 , -14170 , -14159 , -14151 , -14149 , -14145 , -14140 , -14137 , -14135 , -14125 , -14123 , -14122 , -14112 , -14109 , -14099 , -14097 , -14094 , -14092 , -14090 , -14087 , -14083 , -13917 , -13914 , -13910 , -13907 , -13906 , -13905 , -13896 , -13894 , -13878 , -13870 , -13859 , -13847 , -13831 , -13658 , -13611 , -13601 , -13406 , -13404 , -13400 , -13398 , -13395 , -13391 , -13387 , -13383 , -13367 , -13359 , -13356 , -13343 , -13340 , -13329 , -13326 , -13318 , -13147 , -13138 , -13120 , -13107 , -13096 , -13095 , -13091 , -13076 , -13068 , -13063 , -13060 , -12888 , -12875 , -12871 , -12860 , -12858 , -12852 , -12849 , -12838 , -12831 , -12829 , -12812 , -12802 , -12607 , -12597 , -12594 , -12585 , -12556 , -12359 , -12346 , -12320 , -12300 , -12120 , -12099 , -12089 , -12074 , -12067 , -12058 , -12039 , -11867 , -11861 , -11847 , -11831 , -11798 , -11781 , -11604 , -11589 , -11536 , -11358 , -11340 , -11339 , -11324 , -11303 , -11097 , -11077 , -11067 , -11055 , -11052 , -11045 , -11041 , -11038 , -11024 , -11020 , -11019 , -11018 , -11014 , -10838 , -10832 , -10815 , -10800 , -10790 , -10780 , -10764 , -10587 , -10544 , -10533 , -10519 , -10331 , -10329 , -10328 , -10322 , -10315 , -10309 , -10307 , -10296 , -10281 , -10274 , -10270 , -10262 , -10260 , -10256 , -10254 };
        /**/
        /// <summary>
        /// 包含汉字拼音的字符串数组。
        /// </summary>
        private static string[] ps = new string[] { "a" , "ai" , "an" , "ang" , "ao" , "ba" , "bai" , "ban" , "bang" , "bao" , "bei" , "ben" , "beng" , "bi" , "bian" , "biao" , "bie" , "bin" , "bing" , "bo" , "bu" , "ca" , "cai" , "can" , "cang" , "cao" , "ce" , "ceng" , "cha" , "chai" , "chan" , "chang" , "chao" , "che" , "chen" , "cheng" , "chi" , "chong" , "chou" , "chu" , "chuai" , "chuan" , "chuang" , "chui" , "chun" , "chuo" , "ci" , "cong" , "cou" , "cu" , "cuan" , "cui" , "cun" , "cuo" , "da" , "dai" , "dan" , "dang" , "dao" , "de" , "deng" , "di" , "dian" , "diao" , "die" , "ding" , "diu" , "dong" , "dou" , "du" , "duan" , "dui" , "dun" , "duo" , "e" , "en" , "er" , "fa" , "fan" , "fang" , "fei" , "fen" , "feng" , "fo" , "fou" , "fu" , "ga" , "gai" , "gan" , "gang" , "gao" , "ge" , "gei" , "gen" , "geng" , "gong" , "gou" , "gu" , "gua" , "guai" , "guan" , "guang" , "gui" , "gun" , "guo" , "ha" , "hai" , "han" , "hang" , "hao" , "he" , "hei" , "hen" , "heng" , "hong" , "hou" , "hu" , "hua" , "huai" , "huan" , "huang" , "hui" , "hun" , "huo" , "ji" , "jia" , "jian" , "jiang" , "jiao" , "jie" , "jin" , "jing" , "jiong" , "jiu" , "ju" , "juan" , "jue" , "jun" , "ka" , "kai" , "kan" , "kang" , "kao" , "ke" , "ken" , "keng" , "kong" , "kou" , "ku" , "kua" , "kuai" , "kuan" , "kuang" , "kui" , "kun" , "kuo" , "la" , "lai" , "lan" , "lang" , "lao" , "le" , "lei" , "leng" , "li" , "lia" , "lian" , "liang" , "liao" , "lie" , "lin" , "ling" , "liu" , "long" , "lou" , "lu" , "lv" , "luan" , "lue" , "lun" , "luo" , "ma" , "mai" , "man" , "mang" , "mao" , "me" , "mei" , "men" , "meng" , "mi" , "mian" , "miao" , "mie" , "min" , "ming" , "miu" , "mo" , "mou" , "mu" , "na" , "nai" , "nan" , "nang" , "nao" , "ne" , "nei" , "nen" , "neng" , "ni" , "nian" , "niang" , "niao" , "nie" , "nin" , "ning" , "niu" , "nong" , "nu" , "nv" , "nuan" , "nue" , "nuo" , "o" , "ou" , "pa" , "pai" , "pan" , "pang" , "pao" , "pei" , "pen" , "peng" , "pi" , "pian" , "piao" , "pie" , "pin" , "ping" , "po" , "pu" , "qi" , "qia" , "qian" , "qiang" , "qiao" , "qie" , "qin" , "qing" , "qiong" , "qiu" , "qu" , "quan" , "que" , "qun" , "ran" , "rang" , "rao" , "re" , "ren" , "reng" , "ri" , "rong" , "rou" , "ru" , "ruan" , "rui" , "run" , "ruo" , "sa" , "sai" , "san" , "sang" , "sao" , "se" , "sen" , "seng" , "sha" , "shai" , "shan" , "shang" , "shao" , "she" , "shen" , "sheng" , "shi" , "shou" , "shu" , "shua" , "shuai" , "shuan" , "shuang" , "shui" , "shun" , "shuo" , "si" , "song" , "sou" , "su" , "suan" , "sui" , "sun" , "suo" , "ta" , "tai" , "tan" , "tang" , "tao" , "te" , "teng" , "ti" , "tian" , "tiao" , "tie" , "ting" , "tong" , "tou" , "tu" , "tuan" , "tui" , "tun" , "tuo" , "wa" , "wai" , "wan" , "wang" , "wei" , "wen" , "weng" , "wo" , "wu" , "xi" , "xia" , "xian" , "xiang" , "xiao" , "xie" , "xin" , "xing" , "xiong" , "xiu" , "xu" , "xuan" , "xue" , "xun" , "ya" , "yan" , "yang" , "yao" , "ye" , "yi" , "yin" , "ying" , "yo" , "yong" , "you" , "yu" , "yuan" , "yue" , "yun" , "za" , "zai" , "zan" , "zang" , "zao" , "ze" , "zei" , "zen" , "zeng" , "zha" , "zhai" , "zhan" , "zhang" , "zhao" , "zhe" , "zhen" , "zheng" , "zhi" , "zhong" , "zhou" , "zhu" , "zhua" , "zhuai" , "zhuan" , "zhuang" , "zhui" , "zhun" , "zhuo" , "zi" , "zong" , "zou" , "zu" , "zuan" , "zui" , "zun" , "zuo" };
        /**/
        /// <summary>
        /// 包含要排除处理的字符的字符串数组。
        /// </summary>
        private static string[] bd = new string[] {"，", "。", "“", 
    "”", "‘", "’", "￥", "＄", "（", "「", "『", "）", "」", "』", "［", "〖", "【", "］", "〗", "】", "—", "…", "《", "＜", "》", "＞" };


        /**/
        /// <summary>
        /// 设置或获取包含列外词组读音的键/值对的组合。
        /// </summary>
        private static Hashtable _Phrase;

        /**/
        /// <summary>
        /// 设置或获取包含列外词组读音的键/值对的组合。
        /// </summary>
        public static Hashtable Phrase
        {
            get
            {
                if (_Phrase == null)
                {
                    _Phrase = new Hashtable();
                    _Phrase.Add("重庆" , "Chong Qing");
                    _Phrase.Add("深圳" , "Shen Zhen");
                    _Phrase.Add("什么" , "Shen Me");
                }
                return _Phrase;
            }
            set
            {
                _Phrase = value;
            }
        }
        /**/
        /// <summary>
        /// 将指定中文字符串转换为拼音形式。
        /// </summary>
        /// <param name="chs">要转换的中文字符串。</param>
        /// <param name="separator">连接拼音之间的分隔符。</param>
        /// <param name="initialCap">指定是否将首字母大写。</param>
        /// <returns>包含中文字符串的拼音的字符串。</returns>
        public static string Convert(string chs , string separator , bool initialCap)
        {
            if (chs == null || chs.Length == 0)
                return "";
            if (separator == null || separator.Length == 0)
                separator = "";
            // 例外词组
            foreach (DictionaryEntry de in 汉字转拼音.Phrase)
            {
                chs = chs.Replace(de.Key.ToString() , String.Format(" {0} " , de.Value.ToString().Replace(" " , separator)));
            }
            byte[] array = new byte[2];
            string returnstr = "";
            int chrasc = 0;
            int i1 = 0;
            int i2 = 0;
            bool b = false;
            char[] nowchar = chs.ToCharArray();
            CultureInfo ci = Thread.CurrentThread.CurrentCulture;
            TextInfo ti = ci.TextInfo;
            for (int j = 0; j < nowchar.Length; j++)
            {
                array = Encoding.Default.GetBytes(nowchar[j].ToString());
                string s = nowchar[j].ToString();

                if (array.Length == 1)
                {
                    b = true;
                    returnstr += s;
                }
                else
                {
                    if (s == "？")
                    {
                        if (returnstr == "" || b == true)
                            returnstr += s;
                        else
                            returnstr += separator + s;
                        continue;
                    }
                    i1 = (short)(array[0]);
                    i2 = (short)(array[1]);
                    chrasc = i1 * 256 + i2 - 65536;
                    for (int i = (pv.Length - 1); i >= 0; i--)
                    {
                        if (pv[i] <= chrasc)
                        {
                            s = ps[i];
                            if (initialCap == true)
                                s = ti.ToTitleCase(s);
                            if (returnstr == "" || b == true)
                                returnstr += s;
                            else
                                returnstr += separator + s;
                            break;
                        }
                    }
                    b = false;
                }
            }
            returnstr = returnstr.Replace(" " , separator);
            return returnstr;
        }
        /**/
        /// <summary>
        /// 将指定中文字符串转换为拼音形式。
        /// </summary>
        /// <param name="chs">要转换的中文字符串。</param>
        /// <param name="separator">连接拼音之间的分隔符。</param>
        /// <returns>包含中文字符串的拼音的字符串。</returns>
        public static string Convert(string chs , string separator)
        {
            return 汉字转拼音.Convert(chs , separator , false);
        }
        /**/
        /// <summary>
        /// 将指定中文字符串转换为拼音形式。
        /// </summary>
        /// <param name="chs">要转换的中文字符串。</param>
        /// <param name="initialCap">指定是否将首字母大写。</param>
        /// <returns>包含中文字符串的拼音的字符串。</returns>
        public static string Convert(string chs , bool initialCap)
        {
            return 汉字转拼音.Convert(chs , "" , initialCap);
        }
        /**/
        /// <summary>
        /// 将指定中文字符串转换为拼音形式。
        /// </summary>
        /// <param name="chs">要转换的中文字符串。</param>
        /// <returns>包含中文字符串的拼音的字符串。</returns>
        public static string Convert(string chs)
        {
            return 汉字转拼音.Convert(chs , "");
        }


    }

    /// <summary>
    /// 创建任务计划,封好删除、获得所有任务判断任务是否存在、创建任务
    /// </summary>
    public class SchTaskExt
    {
        //引用 c:\windows\system32\taskschd.dll

        //注意：

        //1.引用taskachd.dll后选中按下F4在属性中将 嵌入互操作类型 改为 False (没设置会报一个错误: 无法嵌入互操作类型“TaskScheduler.TaskSchedulerClass”。请改用适用的接口。 )

        //2.schdule.Connec("pc-name 或者 ip","username","domain","password")

        //3.触发器类型有多种选择(按天IDailyTrigger,按分钟ITimeTrigger))；

        //触发频率(Interval)的格式需要遵循"PT1H1M"这样的格式；

        //起始时间需要遵循"YYYY-MM-DDThh:mm:ss"这样的格式。

        /// <summary>
        /// delete task
        /// 删除任务
        /// </summary>
        /// <param name="taskName">要删除任务名字</param>
        private static void DeleteTask(string taskName)
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();
            ts.Connect(null , null , null , null);
            ITaskFolder folder = ts.GetFolder("\\");
            folder.DeleteTask(taskName , 0);
        }

        /// <summary>
        /// get all tasks
        /// 获得所有任务
        /// </summary>
        public static IRegisteredTaskCollection GetAllTasks()
        {
            TaskSchedulerClass ts = new TaskSchedulerClass();
            ts.Connect(null , null , null , null);
            ITaskFolder folder = ts.GetFolder("\\");
            IRegisteredTaskCollection tasks_exists = folder.GetTasks(1);
            return tasks_exists;
        }
        /// <summary>
        /// check task isexists
        /// 判断任务是否存在
        /// </summary>
        /// <param name="taskName"></param>
        /// <returns></returns>
        public static bool IsExists(string taskName)
        {
            var isExists = false;
            IRegisteredTaskCollection tasks_exists = GetAllTasks();
            for (int i = 1; i <= tasks_exists.Count; i++)
            {
                IRegisteredTask t = tasks_exists[i];
                if (t.Name.Equals(taskName))
                {
                    isExists = true;
                    break;
                }
            }
            return isExists;
        }

        /// <summary>
        /// create task
        /// </summary>
        /// <param name="creator"></param>
        /// <param name="taskName"></param>
        /// <param name="path"></param>
        /// <param name="interval"></param>
        /// <returns>state</returns>
        public static _TASK_STATE CreateTaskScheduler(string creator , string taskName , string path , string interval)
        {
            try
            {
                if (IsExists(taskName))
                {
                    DeleteTask(taskName);
                }

                //new scheduler
                TaskSchedulerClass scheduler = new TaskSchedulerClass();
                //pc-name/ip,username,domain,password
                scheduler.Connect(null , null , null , null);
                //get scheduler folder
                ITaskFolder folder = scheduler.GetFolder("\\");


                //set base attr 
                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author = "McodsAdmin";//creator
                task.RegistrationInfo.Description = "...";//description

                //set trigger  (IDailyTrigger ITimeTrigger)
                ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                tt.Repetition.Interval = interval;// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器
                tt.StartBoundary = "2015-04-09T14:27:25";//start time

                //set action
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = path;

                task.Settings.ExecutionTimeLimit = "PT0S"; //运行任务时间超时停止任务吗? PTOS 不开启超时
                task.Settings.DisallowStartIfOnBatteries = false;//只有在交流电源下才执行
                task.Settings.RunOnlyIfIdle = false;//仅当计算机空闲下才执行

                IRegisteredTask regTask =
                    folder.RegisterTaskDefinition(taskName , task ,
                    (int)_TASK_CREATION.TASK_CREATE , null , //user 
                    null , // password
                    _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN , "")
                    ;
                IRunningTask runTask = regTask.Run(null);
                return runTask.State;

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }

    public class errorRecord
    {
        /// <summary>
        /// 记录错误信息，默认./error.data
        /// </summary>
        public errorRecord()
        {
            save_location = @"./error.data";
            初始化();
        }
        public errorRecord(string saveLocation)
        {
            save_location = saveLocation;
            初始化();
        }

        private List<string> buffer
        {

            set
            {
                _buffer = value;
            }
            get
            {
                return _buffer;
            }
        }

        /// <summary>
        /// 后台写入
        /// </summary>
        private bool background_write
        {
            set
            {
                _write = value;
            }
            get
            {
                return _write;
            }
        }

        /// <summary>
        /// 保存多少
        /// </summary>
        private int num
        {
            set
            {
                _num = value;
            }
            get
            {
                return _num;
            }
        }

        

        /// <summary>
        /// 如果bufferB正在写，Bwrite==true，不能对bufferB操作
        /// </summary>
        private bool Bwrite
        {
            set
            {
                _Bwrite = value;
            }
            get
            {
                return _Bwrite;
            }
        }

        /// <summary>
        /// 如果bufferA正在写，Awrite==true，不能对bufferA操作
        /// </summary>
        private bool Awrite
        {

            set
            {
                _Awrite = value;
            }
            get
            {
                return _Awrite;
            }
        }

        /// <summary>
        /// 缓冲B
        /// </summary>
        private List<string> bufferB
        {
            set
            {
                _bufferB = value;
            }
            get
            {
                return _bufferB;
            }
        }

        /// <summary>
        /// 缓冲
        /// </summary>
        private List<string> bufferA
        {
            set
            {
                _bufferA = value;
            }
            get
            {
                return _bufferA;
            }
        }
        private string save_location
        {
            set
            {
                _save_location = value;
            }
            get
            {
                return _save_location;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="record">要记录,自动末尾"\n"</param>
        public void write(string record)
        {            
            //List<string> buffer;

            ////如果A写入
            //if(!Awrite && !Bwrite && bufferA.Count==0 && bufferB.Count>0)
            //{
            //    Bwrite = true;
            //    record_file(bufferB,false);
            //}
            //else if(!Awrite && bufferA.Count>=10 && !Bwrite)
            //{
            //    Awrite = true;
            //    record_file(bufferA , true);
            //}

            ////如果A在写
            //if(Awrite)
            //{
            //    buffer = bufferB;
            //}
            //else
            //{
            //    buffer = bufferA;
            //}

            //记录
            buffer.Add(record + "\n");
            if(buffer.Count>10 && !Awrite && !Bwrite)
            {
               if(buffer.Equals(bufferA))
               {
                   Awrite = true;
                   record_file(bufferA , true);
                   buffer = bufferB;
               }
               else
               {
                   Bwrite = true;
                   record_file(bufferB , false);
                   buffer = bufferA;
               }
            }
        }
        ~errorRecord()
        {
           if(buffer.Count>0)
           {
               record_fileAsync();
           }
        }

        private async Task record_fileAsync()
        {
            StringBuilder a = new StringBuilder();
            foreach (var str in buffer)
            {
                //file.Write(str);
                a.Append(str);
            }
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(save_location , true))
            {
                string str;
                str = a.ToString();
                await file.WriteAsync(str);
            }
            buffer.Clear();            
        }        
        private async Task record_file(List<string> buffer,bool write)
        {
            StringBuilder a = new StringBuilder();
            foreach (var str in buffer)
            {
                //file.Write(str);
                a.Append(str);
            }
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(save_location , true))
            {
                string str;
                str = a.ToString();
                await file.WriteAsync(str);
            }
            buffer.Clear();
            if(write)
            {
                Awrite = false;
            }
            else
            {
                Bwrite = false;
            }
        }        
        private void 初始化()
        {
            Awrite = false;
            Bwrite = false;

            num = -1;
            background_write = false;
            buffer = bufferA;
        }        

        private string _save_location;
        private List<string> _bufferA = new List<string>();
        private List<string> _bufferB = new List<string>();
        private bool _Awrite;
        private bool _Bwrite;
        private int _num;
        private bool _write;
        private List<string> _buffer;
    }

    //public class GWindow : Window
    //{
    //    //托盘
    //    NotifyIcon notifyIcon;

    //    //注册AreaIcon属性，用于托盘的图标
    //    public static readonly DependencyProperty AreaIconProperty =
    //        DependencyProperty.Register("AreaIcon" , typeof(ImageSource) , typeof(GWindow));
    //    //注册AreaText属性，用于鼠标滑到托盘图标时显示的文字
    //    public static readonly DependencyProperty AreaTextProperty =
    //        DependencyProperty.Register("AreaText" , typeof(string) , typeof(GWindow));
    //    //注册AreaVisibility属性，用于显示隐藏托盘图标
    //    public static readonly DependencyProperty AreaVisibilityProperty =
    //        DependencyProperty.Register("AreaVisibility" , typeof(bool) , typeof(GWindow));
    //    //注册AreaMenuItems属性，用于托盘右键在单的列表
    //    public static readonly DependencyProperty AreaMenuItemsProperty =
    //        DependencyProperty.Register("AreaMenuItems" , typeof(List<MenuItem>) , typeof(GWindow) , new PropertyMetadata(new List<MenuItem>()));

    //    protected override void OnInitialized(EventArgs e)
    //    {
    //        base.OnInitialized(e);

    //        notifyIcon = new NotifyIcon();
    //        notifyIcon.Text = AreaText;
    //        if (!DesignerProperties.GetIsInDesignMode(this))
    //        {
    //            notifyIcon.Icon = GetImageSource(AreaIcon);
    //        }
    //        notifyIcon.Visible = AreaVisibility;

    //        if (this.AreaMenuItems != null && this.AreaMenuItems.Count > 0)
    //        {
    //            notifyIcon.ContextMenu = new ContextMenu(this.AreaMenuItems.ToArray());
    //        }
    //    }

    //    public List<MenuItem> AreaMenuItems
    //    {
    //        get
    //        {
    //            return (List<MenuItem>)GetValue(AreaMenuItemsProperty);
    //        }
    //        set
    //        {
    //            SetValue(AreaMenuItemsProperty , value);
    //        }
    //    }

    //    public ImageSource AreaIcon
    //    {
    //        get
    //        {
    //            return (ImageSource)GetValue(AreaIconProperty);
    //        }
    //        set
    //        {
    //            SetValue(IconProperty , value);
    //        }
    //    }

    //    public string AreaText
    //    {
    //        get
    //        {
    //            return (string)GetValue(AreaTextProperty);
    //        }
    //        set
    //        {
    //            SetValue(AreaTextProperty , value);
    //        }
    //    }

    //    public bool AreaVisibility
    //    {
    //        get
    //        {
    //            return (bool)GetValue(AreaVisibilityProperty);
    //        }
    //        set
    //        {
    //            SetValue(AreaVisibilityProperty , value);
    //        }
    //    }

    //    protected override void OnClosing(CancelEventArgs e)
    //    {
    //        base.OnClosing(e);
    //        notifyIcon.Visible = false;
    //        notifyIcon.Dispose();
    //        AreaMenuItems.Clear();
    //    }

    //    private static Drawing.Icon GetImageSource(ImageSource icon)
    //    {
    //        if (icon == null)
    //        {
    //            return null;
    //        }
    //        Uri iconUri = new Uri(icon.ToString());
    //        return new Drawing.Icon(System.Windows.Application.GetResourceStream(iconUri).Stream);
    //    }
    //}
}
